/*子应用*/
const express = require('express');

const query = require('../pool');

const changePwd = express.Router();

const sms = require('../modules/login/smscode');



// 获取验证码
changePwd.get('/mobile?:phone',async(req,res)=>{
  let obj = req.query;
  // 查询是否存在该手机号用户
  let rows = await query('select 1 as num from cake_user where phone = ? and upwd is not null',[obj.phone]);
  if(rows.length==0){
    res.send({code:0,msg:'该手机号不存在,请注册'});
  }else{
    let smscode = await sms(obj.phone);
    let result =await query('update cake_user set changePwdcode = ? where phone = ?',[smscode,obj.phone]);
    if(result.affectedRows==0){
      res.send({code:0,msg:'数据插入失败'})
    }else{
      res.send({code:1,msg:"验证码插入数据成功"})
    }
  }
})

// 修改密码
changePwd.post('/',async(req,res)=>{
  let obj = req.body;
  let rows =await query('select 1 from cake_user where phone = ? and changePwdcode = ?',[obj.phone,obj.telCode]);
  // console.log(rows);
  if(rows.length==0){
    res.send({code:0,msg:"验证码不正确"})
  }else{
    let result = await query('update cake_user set upwd = md5(?) where phone = ?',[obj.upwd,obj.phone]);
    if(result.length==0){
      res.send({code:0,msg:'密码修改失败'})
    }else{
      res.send({code:1,msg:'密码修改成功'})
    }
  }
})

//暴露
module.exports = changePwd;
